const express = require('express');
const { Op } = require('sequelize');
const { User } = require('../../models');
const router = express.Router();
const { usersFilterBody } = require('../../utils/filter-req');
const { success, failure } = require('../../utils/responses');
const { NotFound } = require('http-errors');

// if (isPasswordValid) {
//     // ...
// }

const getList = async (req) => {
  const { id } = req.params;
  const users = await User.findByPk(id);
  if (!users) {
    throw new NotFound(`ID：${id}不存在`);
  }
  return users;
};
router.get('/', async (req, res) => {
  try {
    let { email, username, nickname, role, currentPage, pageSize } = req.query;
    pageSize = Math.abs(Number(pageSize || 10));
    currentPage = Math.abs(Number(currentPage || 1));

    const condition = {
      where: {},
      order: [['id', 'DESC']],
      limit: pageSize,
      offset: (currentPage - 1) * pageSize,
    };

    if (email) {
      condition.where.email = email;
    }

    if (username) {
      condition.where.username = username;
    }

    if (nickname) {
      condition.where.nickname = {
        [Op.like]: `%${nickname}%`,
      };
    }

    if (role) {
      condition.where.role = role;
    }

    const { count, rows } = await User.findAndCountAll(condition);

    const data = {
      data: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    };
    success({
      res,
      data,
    });
  } catch (error) {
    // 返回错误信息
    failure({ res, error });
  }
});

/**
 * 查询当前登录的用户详情
 * GET /admin/users/me
 * 还有一个要注意的是，这个新增的方法，必须在/:id路由的上面。这是因为路由是按顺序依次匹配的，上面的匹配到了，就不会继续向下匹配了。

如果你将/me方法，丢在下面了。访问接口的时候，就只会先匹配到/:id方法，它会把me当成是一个id值来进行查询的，这就错了
 */
router.get('/me', async function (req, res) {
  try {
    const user = req.user;
    success({ res, message: '查询当前用户信息成功。', data: user });
  } catch (error) {
    failure({ res, error });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const category = await getList(req);
    success({ res, data: category });
  } catch (error) {
    failure({ res, error });
  }
});
router.post('/', async (req, res) => {
  try {
    const body = usersFilterBody(req.body);

    await User.create(body);
    //200状态么和201不同， 201表示请求成功并且创建新的资源 更专业
    success({ res, code: 201, message: '创建成功' });
  } catch (error) {
    failure({ res, error, message: '创建失败' });
  }
});
// router.delete('/:id', async (req, res) => {
//     try {
//         const category = await getList(req)
//         //删除
//         await category.destroy()
//         success({ res, message: '删除成功' })

//     } catch (error) {
//         failure({ res, error, message: '删除失败' })
//     }
// })

router.put('/:id', async (req, res) => {
  try {
    const users = await getList(req);
    const body = usersFilterBody(req.body);
    await users.update(body);
    success({ res, message: '更新成功' });
  } catch (error) {
    failure({ res, error });
  }
});

module.exports = router;
